package com.hsy.swu.home.textbook

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.room.Room
import com.hsy.swu.databinding.FragmentTextbookBinding
import com.hsy.swu.home.HomeFragmentViewModel
import com.hsy.swu.hsyutils.HsyFragment
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.hsyutils.MLog
import com.hsy.swu.roomdb.AppDatabase
import com.hsy.swu.roomdb.TextbookDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class TextbookFragment : HsyFragment<FragmentTextbookBinding, HomeFragmentViewModel>() {
    private lateinit var textbookDao: TextbookDao

    override fun createViewModel(): HomeFragmentViewModel {
        return ViewModelProvider(requireActivity())[HomeFragmentViewModel::class.java]
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.rvTextbook.apply {
            adapter = TextbookAdapter()
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }

        textbookDao = Room.databaseBuilder(
            requireContext(), AppDatabase::class.java, "swu"
        ).build().textbookDao()
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            getTextbookFromRoomDBAndRefreshUI()
        }
        mViewModel.mBinder?.getService()?.setGetTextbookListener { textbookList ->
            MLog.attention("got textbook -> ${textbookList.size}")
            if (textbookList.isEmpty()) return@setGetTextbookListener
            lifecycleScope.launch {
                if (isResumed) {
                    getTextbookFromRoomDBAndRefreshUI()
                }
            }
        }
    }

    private suspend fun getTextbookFromRoomDBAndRefreshUI() {
        var textbookDBList: List<TextbookModel>
        withContext(Dispatchers.IO) {
            textbookDBList = textbookDao.getAll()
        }
        (mBinding.rvTextbook.adapter as TextbookAdapter).textbookList = textbookDBList

        if (textbookDBList.isNotEmpty()) {
            MActivityUtil.alphaAnimGoneLottieEmpty(mBinding.lottieEmpty)
        } else {
            MActivityUtil.alphaAnimVisibleLottieEmpty(mBinding.lottieEmpty)
        }
    }
}